package cn.itcast.aspect;

import cn.itcast.controller.BaseController;
import cn.itcast.entity.Employee;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class UpdateAndSaveAdvice {
    @Autowired
  private   HttpSession session;

    @Before("execution(* cn.itcast.service.*.save(..))")
    @SneakyThrows
    public void beforeSave(JoinPoint joinPoint){

        Object[] args = joinPoint.getArgs();
        Object employee = args[0];
        Class<?> clazz = args[0].getClass();
        Method setCreateTimeMethod = clazz.getMethod("setCreateTime", LocalDateTime.class);
        setCreateTimeMethod.invoke(employee,LocalDateTime.now());
        Method setUpdateTimeMethod = clazz.getMethod("setUpdateTime", LocalDateTime.class);
        setUpdateTimeMethod.invoke(employee,LocalDateTime.now());
        Long id = (Long) session.getAttribute("LOGIN_ID");
        System.out.println(id);
        Method setCreateUserMethod = clazz.getMethod("setCreateUser", Long.class);
        setCreateUserMethod.invoke(employee,id);

        Method setUpdateUserMethod = clazz.getMethod("setUpdateUser", Long.class);
        setUpdateUserMethod.invoke(employee,id);

    }


    @Before("execution(* cn.itcast.service.*.update*(..))")
    @SneakyThrows
    public void beforeUpdate(JoinPoint joinPoint){

        Object[] args = joinPoint.getArgs();
        Object employee = args[0];
        Class<?> clazz = args[0].getClass();

        Method setUpdateTimeMethod = clazz.getMethod("setUpdateTime", LocalDateTime.class);
        setUpdateTimeMethod.invoke(employee,LocalDateTime.now());

        Long id = (Long) session.getAttribute("LOGIN_ID");
        Method setUpdateUserMethod = clazz.getMethod("setUpdateUser", Long.class);
        setUpdateUserMethod.invoke(employee,id);

        log.info("{}的属性值自动设置完成",employee);
    }
}
